"""
告警服务
处理系统告警和通知
"""

import asyncio
import json
from datetime import datetime
from typing import Dict, Any, List, Callable
from src.utils.logging import get_logger
from src.services.monitoring_service import monitoring_service

logger = get_logger(__name__)


class AlertService:
    """告警服务类"""
    
    def __init__(self):
        self.alerts: Dict[str, Any] = {}
        self.alert_handlers: List[Callable[..., Any]] = []
        self.enabled = True
        logger.info("告警服务初始化完成")
    
    def register_alert_handler(self, handler: Callable[..., Any]):
        """
        注册告警处理器
        
        Args:
            handler: 告警处理函数
        """
        self.alert_handlers.append(handler)
        logger.info(f"已注册告警处理器，当前共有 {len(self.alert_handlers)} 个处理器")
    
    async def process_alert(self, alert_data: Dict[str, Any]):
        """
        处理告警
        
        Args:
            alert_data: 告警数据
        """
        if not self.enabled:
            return
            
        alert_key = f"{alert_data.get('labels', {}).get('alertname', 'unknown')}_{alert_data.get('labels', {}).get('instance', 'unknown')}"
        
        try:
            # 记录告警
            self.alerts[alert_key] = {
                "data": alert_data,
                "timestamp": datetime.now(),
                "status": "active"
            }
            
            logger.warning(f"收到告警: {alert_data}")
            
            # 调用所有告警处理器
            for handler in self.alert_handlers:
                try:
                    await handler(alert_data)
                except Exception as e:
                    logger.error(f"告警处理器执行失败: {e}")
                    
        except Exception as e:
            logger.error(f"处理告警失败: {e}")
    
    async def resolve_alert(self, alert_key: str):
        """
        解决告警
        
        Args:
            alert_key: 告警键
        """
        if alert_key in self.alerts:
            self.alerts[alert_key]["status"] = "resolved"
            self.alerts[alert_key]["resolved_at"] = datetime.now()
            logger.info(f"告警已解决: {alert_key}")
    
    def get_active_alerts(self) -> List[Dict[str, Any]]:
        """
        获取活跃告警列表
        
        Returns:
            活跃告警列表
        """
        return [alert for alert in self.alerts.values() if alert["status"] == "active"]
    
    def get_alert_statistics(self) -> Dict[str, int]:
        """
        获取告警统计信息
        
        Returns:
            告警统计信息
        """
        active_count = len([a for a in self.alerts.values() if a["status"] == "active"])
        resolved_count = len([a for a in self.alerts.values() if a["status"] == "resolved"])
        
        return {
            "total": len(self.alerts),
            "active": active_count,
            "resolved": resolved_count
        }


# 全局告警服务实例
alert_service = AlertService()


# 告警处理示例函数
async def email_alert_handler(alert_data: Dict[str, Any]):
    """邮件告警处理器"""
    # 这里可以实现发送邮件的逻辑
    logger.info(f"通过邮件发送告警: {alert_data.get('annotations', {}).get('summary', '无摘要')}")


async def webhook_alert_handler(alert_data: Dict[str, Any]):
    """Webhook告警处理器"""
    # 这里可以实现发送Webhook的逻辑
    logger.info(f"通过Webhook发送告警: {alert_data.get('labels', {})}")


# 注册默认告警处理器
alert_service.register_alert_handler(email_alert_handler)
alert_service.register_alert_handler(webhook_alert_handler)